package com.java.mall_imooc.common.utils;

import com.java.mall_imooc.common.enums.ResultEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 响应信息主体
 * @author jiangli
 * @since 2020-03-15 21:57
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer code;

    private String msg;

    private T data;

    public static <T> R<T> ok() {
        return restResult(null, ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ResultEnum.SUCCESS.getCode(), null);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, ResultEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> error(String msg) {
        return restResult(null, ResultEnum.ERROR.getCode(), msg);
    }

    public static <T> R<T> error(Integer code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> error(ResultEnum e) {
        return restResult(null, e.getCode(), e.getMessage());
    }

    private static <T> R<T> restResult(T data, Integer code, String msg) {
        R<T> apiResult = new R<T>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

}

